package br.com.lumis.saas.service.consumerclient.processaction;

import java.util.Collection;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.group.GroupConfig;
import lumis.portal.manager.ManagerException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.user.UserConfig;
import lumis.util.XmlUtil;
import lumis.util.log.ILogger;
import lumis.util.log.LoggerFactory;
import br.com.lumis.saas.SaasRequestParameters;
import br.com.lumis.saas.service.consumerclient.persistence.dao.CustomerDAO;

@SuppressWarnings("unchecked")
public class CustomerProcessActionHandler extends ProcessActionHandler<Source> {
	private static final ILogger LOGGER = LoggerFactory
			.getLogger(CustomerProcessActionHandler.class);
	private static final String CUSTOMER_ADD = "addCustomer";

	private CustomerDAO customerDAO = new CustomerDAO();

	
	public void processAction() throws PortalException {
		String actionType = XmlUtil.readAttributeString(
				SaasRequestParameters.ACTIONTYPE, processActionNode, "");

		if (actionType.equals(CUSTOMER_ADD))
			processAddCustomer();
	}

	/*
	 * Create object user in lum_user
	 */
	private void processAddCustomer() {
		try {
			String id = getParameter(SaasRequestParameters.PAGE_PARAMETER_ID,
					String.class);
			String name = getParameter(
					SaasRequestParameters.PAGE_PARAMETER_NAME, String.class);
			String login = getParameter(
					SaasRequestParameters.PAGE_PARAMETER_LOGIN, String.class);
			String email = getParameter(
					SaasRequestParameters.PAGE_PARAMETER_EMAIL, String.class);
			String password = getParameter(
					SaasRequestParameters.PAGE_PARAMETER_PASSWORD, String.class);

			UserConfig userConfig = new UserConfig();
			userConfig.setId(id);
			userConfig.setFirstName(name);
			userConfig.setLogin(login);
			userConfig.setPassword(password);
			userConfig.setEmail(email);
			userConfig.setChannelId(SaasRequestParameters.SAAS_CHANNEL_ID);

			String lumUserId = ManagerFactory.getUserManager().add(
					sessionConfig, userConfig, transaction);

			Collection<GroupConfig> groups = ManagerFactory.getGroupManager()
					.getByChannelId(sessionConfig,
							SaasRequestParameters.SAAS_CHANNEL_ID, transaction);

			for (GroupConfig groupConfig : groups) {
				if (groupConfig.getAlias().equals("saas.Clientes"))
					ManagerFactory.getGroupManager().addMember(sessionConfig,
							groupConfig.getId(), userConfig.getId(),
							transaction);
			}

			customerDAO.updateLumUserId(name, lumUserId, transaction);

			addDefaultResponse();

		} catch (ManagerException e) {
			LOGGER.error(e);
		} catch (PortalException e) {
			LOGGER.error(e);
		}
	}
}
